
package com.demo.test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author LMH
 * @version 创建时间：2019年7月17日 下午2:40:30
 * 
 * RedisTemplate封装了从JedisPool中取jedis以及返回池中
 */
public class RedisTemplate {

	private JedisPool jedisPool;

	public RedisTemplate(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	public <T> T execute(RedisCallback<T> callback) {
		Jedis jedis = jedisPool.getResource();
		try {
			return callback.handle(jedis);
		} catch (Exception e) {
			throw e;
		} finally {
			returnResource(jedis);
		}
	}

	private void returnResource(Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}
}
